<!-- 个人页 -->
<template>
	<view class="profile-container">
		<view class="profile-header">
			<image class="avatar" :src="avatarURL" @click="onChangeAvatar" />
			<view class="nickname" @click="onChangeNickName">{{ nickName }}</view>
		</view>

		<!-- 功能条 -->
		<view class="profile-actions">
			<view class="action-item" @click="navigateToDeviceInfo">
				<text>设备信息</text>
			</view>
			<view class="action-item" @click="navigateToVersionInfo">
				<text>软件版本</text>
			</view>
		</view>

		<button @click="onLogout" class="logout-button">
			退出登录
		</button>

		<!-- 头像选择弹框 -->
		<view v-if="showAvatarPicker" class="avatar-picker-popup">
			<view class="avatar-picker-content">
				<view class="popup-title">选择头像</view>
				<view class="avatar-options">
					<image v-for="(avatar, index) in availableAvatars" :key="index" :src="avatar" class="avatar-option"
						@click="selectAvatar(avatar)" />
				</view>
				<view class="popup-actions">
					<button @click="onCancelAvatarPicker">取消</button>
				</view>
			</view>
		</view>

		<view v-if="showChangeNickName" class="name-edit-popup">
			<view class="name-edit-popup-content">

				<input class="name-input" v-model="newNickName" placeholder="请输入昵称" maxlength="30" />

				<view class="name-popup-actions">
					<button @click="onCancelNickNameEdit">取消</button>
					<button @click="onConfirmNickNameEdit">确定</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getUserProfile,
		wxUserProfile,
		logout
	} from '@/src/api/auth.js'
	import {
		getUserDetailByOpenid,
		editUserAvatar,
		editUserNickName
	} from '@/src/api/user.js'
	export default {
		data() {
			return {
				// 从全局或本地缓存获取用户信息和登录状态
				openid: getApp().globalData.openid || uni.getStorageSync("openid"),
				userInfo: getApp().globalData.userInfo || uni.getStorageSync("userInfo"),
				hasUserInfo: getApp().globalData.hasUserInfo || uni.getStorageSync("hasUserInfo"),
				avatarURL: '/static/avatar/avatar1.jpg',
				nickName: '',
				
				// 头像选择弹框
				showAvatarPicker: false,
				availableAvatars: [
					'/static/avatar/avatar1.jpg',
					'/static/avatar/avatar2.jpg',
					'/static/avatar/avatar3.jpg',
					'/static/avatar/avatar4.jpg',
					'/static/avatar/avatar5.jpg',
					'/static/avatar/avatar6.jpg',
					'/static/avatar/avatar7.jpg'
				],
				
				// 修改昵称
				showChangeNickName: false,
				newNickName: ''
			}
		},
		async onLoad(options) {
			const userDetailResponse = await getUserDetailByOpenid(this.openid)
			console.log("用户详情接口返回： ", userDetailResponse)
			const detail = userDetailResponse.data
			console.log("用户详情： ", detail)
			this.avatarURL = '/static/avatar/' + detail.avatar
			console.log("头像： ", this.avatarURL)
			this.nickName = detail.nickName
		},
		methods: {
			/**
			 * 退出登录
			 */
			async onLogout() {
				try {
					// 如果有后端登出接口，则调用
					const logoutResponse = await logout(this.openid)
					console.log("退出登录logoutResponse = ", logoutResponse)
					if (logoutResponse.status != 200) throw new Error('后端登出失败')

					// 简单处理：直接清除本地和全局信息
					uni.removeStorageSync('openid')
					uni.removeStorageSync('userInfo')
					uni.removeStorageSync('hasUserInfo')
					getApp().globalData.openid = null
					getApp().globalData.userInfo = null
					getApp().globalData.hasUserInfo = false
					this.openid = ''
					this.userInfo = {}
					this.hasUserInfo = false

					uni.showToast({
						title: '退出成功',
						icon: 'success'
					})

					// 退出小程序
					wx.exitMiniProgram({
						success: function() {
							console.log('退出小程序成功')
						},
						fail: function(err) {
							console.error('退出小程序失败', err)
							uni.showToast({
								title: '退出小程序失败',
								icon: 'none'
							})
						}
					})
				} catch (err) {
					console.error('退出登录出错:', err)
					uni.showToast({
						title: '退出失败，请重试',
						icon: 'none'
					})
				}
			},

			/**
			 * 导航到设备信息页
			 */
			navigateToDeviceInfo() {
				uni.navigateTo({
					url: '/pages/deviceInfo/deviceInfo'
				})
			},

			/**
			 * 导航到版本信息页
			 */
			navigateToVersionInfo() {
				uni.navigateTo({
					url: '/pages/versionInfo/versionInfo'
				})
			},

			/**
			 * 修改名称
			 */
			onChangeNickName() {
				this.showChangeNickName = true
			},
			onCancelNickNameEdit(){
				this.showChangeNickName = false
				this.newNickName = ''
			},
			async onConfirmNickNameEdit(){
				let paramObj = {
					openid: this.openid,
					nickName: this.newNickName
				}
				const updateResponse = await editUserNickName(paramObj)
				console.log("更新头像响应：", updateResponse)
				if (updateResponse.status == 200) {
					uni.showToast({
						title: '昵称修改成功',
						icon: 'success'
					})
					this.showChangeNickName = false
					this.nickName = this.newNickName
				} else {
					uni.showToast({
						title: '昵称修改失败',
						icon: 'success'
					})
				}
			},

			/**
			 * 显示头像选择弹框
			 */
			onChangeAvatar() {
				this.showAvatarPicker = true
			},

			/**
			 * 选择头像
			 */
			async selectAvatar(avatarPath) {
				try {
					// 显示加载提示
					uni.showLoading({
						title: '更换头像...',
						mask: true
					})

					// 调用后端API更新头像
					let paramObj = {
						openid: this.openid,
						avatar: avatarPath.split('/').pop()
					}
					const updateResponse = await editUserAvatar(paramObj)
					console.log("更新头像响应：", updateResponse)
					if (updateResponse.status != 200) throw new Error('更新头像失败')

					// 更新前端显示
					this.avatarURL = avatarPath

					uni.showToast({
						title: '头像更新成功',
						icon: 'success'
					})
				} catch (error) {
					console.error('更新头像失败:', error)
					uni.showToast({
						title: '更新头像失败，请重试',
						icon: 'none'
					})
				} finally {
					this.showAvatarPicker = false
					uni.hideLoading()
				}
			},

			/**
			 * 取消头像选择
			 */
			onCancelAvatarPicker() {
				this.showAvatarPicker = false
			}
		}
	}
</script>

<style>
	.profile-container {
		padding: 20px;
	}

	.profile-header {
		display: flex;
		align-items: center;
		margin-bottom: 20px;
	}

	.avatar {
		width: 60px;
		height: 60px;
		border-radius: 50%;
		margin-right: 20px;
		cursor: pointer;
		/* 鼠标悬停时显示为指针 */
	}

	.nickname {
		font-size: 16px;
		font-weight: bold;
	}

	.profile-actions {
		margin-bottom: 20px;
	}

	.action-item {
		display: flex;
		align-items: center;
		padding: 15px;
		background-color: #f9f9f9;
		border-radius: 6px;
		margin-bottom: 10px;
		cursor: pointer;
		transition: background-color 0.3s;
	}

	.action-item:hover {
		background-color: #e6f7ff;
	}

	.action-item text {
		font-size: 16px;
		color: #333;
	}

	.logout-button {
		width: 100%;
		background-color: #F56C6C;
		color: #fff;
		padding: 10px 0;
		margin-top: 10px;
		border-radius: 4px;
		text-align: center;
		font-size: 16px;
	}

	/* 头像选择弹框样式 */
	.avatar-picker-popup {
		position: fixed;
		left: 0;
		right: 0;
		top: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.6);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 10000;
	}

	.avatar-picker-content {
		background: #fff;
		width: 90%;
		max-width: 400px;
		padding: 20px;
		border-radius: 8px;
		box-sizing: border-box;
	}

	.popup-title {
		font-size: 18px;
		font-weight: bold;
		margin-bottom: 20px;
		text-align: center;
	}

	.avatar-options {
		display: flex;
		flex-wrap: wrap;
		justify-content: center;
		gap: 10px;
		margin-bottom: 20px;
	}

	.avatar-option {
		width: 80px;
		height: 80px;
		border-radius: 50%;
		border: 2px solid transparent;
		cursor: pointer;
		transition: border-color 0.3s;
	}

	.avatar-option:hover {
		border-color: #07C160;
	}

	.popup-actions {
		display: flex;
		justify-content: center;
		gap: 20px;
	}

	.popup-actions button {
		flex: 1;
		padding: 10px 0;
		border: none;
		border-radius: 4px;
		cursor: pointer;
		font-size: 16px;
	}

	.popup-actions button:first-child {
		background-color: #ccc;
		color: #fff;
	}

	.popup-actions button:last-child {
		background-color: #07C160;
		color: #fff;
	}

	/* 弹框公共样式 */
	.name-edit-popup {
		position: fixed;
		left: 0;
		right: 0;
		top: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.4);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 9999;
	}

	.name-edit-popup-content {
		background: #fff;
		width: 80%;
		max-width: 400px;
		padding: 20px;
		border-radius: 6px;
		box-sizing: border-box;
		/* 包含内边距 */
	}

	.name-input {
		width: 100%;
		height: 40px;
		padding: 5px 10px;
		border: 1px solid #ccc;
		box-sizing: border-box;
		margin-bottom: 15px;
	}

	.name-popup-title {
		font-size: 16px;
		font-weight: bold;
		margin-bottom: 15px;
	}

	.name-popup-actions {
		display: flex;
		justify-content: flex-end;
		gap: 15px;
	}
</style>